package com.example.servicelocation;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.example.servicelocation.lib.KalmanLocationManager;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private ArrayList<Location> myDataset;

    /**
     * 位置GPS更新时间
     */
    private static final long GPS_TIME = 1000;
    /**
     * 位置网络定位更新时间
     */
    private static final long NET_TIME = 1000;
    /**
     * 过滤器触发时间
     */
    private static final long FILTER_TIME = 1000;
    private  String path;
    private final String fileName="location.text";

    private KalmanLocationManager mKalmanLocationManager;
    private SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
    public static final int RESULT_CODE=1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(path, fileName);

        recyclerView = findViewById(R.id.recyclerview);
        myDataset = new ArrayList<Location>();

        //recyclerView初始化与数据绑定
        recyclerView.setHasFixedSize(false);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter(myDataset);
        recyclerView.setAdapter(adapter);

        //请求权限
        methodRequiresTwoPermission();
    }

    //动态权限框架
    @AfterPermissionGranted(RESULT_CODE)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
            // 已有权限
            mKalmanLocationManager = new KalmanLocationManager(MainActivity.this);
            mKalmanLocationManager.requestLocationUpdates(
                    KalmanLocationManager.UseProvider.GPS_AND_NET, FILTER_TIME, GPS_TIME, NET_TIME, mLocationListener, true);

        } else {

            EasyPermissions.requestPermissions(MainActivity.this, "请求获取您的位置信息和本地读写权限",
                    RESULT_CODE, perms);
        }
    }

    private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {

            if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                Log.e("定位", "GPS定位");
                writeTxtToFile(location,"GPS");
            }

            if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
                Log.e("定位", "网络定位");
                writeTxtToFile(location,"网络");
            }

            if (location.getProvider().equals(KalmanLocationManager.KALMAN_PROVIDER)
            ) {
                Log.e("定位", "卡尔曼滤波结果");
                writeTxtToFile(location,"卡尔曼");
            }
            //数据添加到列表
            myDataset.add(location);
            adapter.notifyDataSetChanged();//通知数据更新
            recyclerView.scrollToPosition(adapter.getItemCount()-1);

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    // 将字符串写入到文本文件中
    private void writeTxtToFile(Location location, String type) {

        Date date = new Date(System.currentTimeMillis());
        String strcontent=location.getLatitude()+","+location.getLongitude()+","+location.getAccuracy()+
                ","+type+","+formatter.format(date);
        String strFilePath = path + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        Log.e("写入内容",strContent);
        try {
            File file = new File(strFilePath);
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();

        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }
    private File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }else {
                file.delete();
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    //生成文件夹
    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

}